package com.fitso.model.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.stereotype.Repository;

import com.fitso.model.bean.nutrition.FoodDescription;
import com.fitso.model.dao.FoodIdentityDao;

@Repository("HibernateFoodIdentityDao")
public class HibernateFoodIdentityDao extends HibernateBaseDao implements FoodIdentityDao {

	public void delete(FoodDescription foodDescription) {
		getTemplate().delete(foodDescription);
	}

	@SuppressWarnings("unchecked")
	public List<FoodDescription> read() {
		return getTemplate().loadAll(FoodDescription.class);
	}

	public List<FoodDescription> readByCommonName(String commonName) {
		DetachedCriteria criteria = DetachedCriteria.forClass(FoodDescription.class);
		criteria.add(Property.forName("commonName").eq(commonName));

		return fetchByCriteria(criteria);
	}

	public FoodDescription readById(Long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(FoodDescription.class);
		criteria.add(Property.forName("id").eq(id));

		return first(fetchByCriteria(criteria), FoodDescription.class);
	}

	public List<FoodDescription> readByProducer(String producer) {
		DetachedCriteria criteria = DetachedCriteria.forClass(FoodDescription.class);
		criteria.add(Property.forName("producer").eq(producer));

		return fetchByCriteria(criteria);
	}

	public List<FoodDescription> readByProductName(String productName) {
		DetachedCriteria criteria = DetachedCriteria.forClass(FoodDescription.class);
		criteria.add(Property.forName("productName").eq(productName));

		return fetchByCriteria(criteria);
	}

	public void createOrUpdate(FoodDescription foodDescription) {
		getTemplate().saveOrUpdate(foodDescription);
	}

	@SuppressWarnings("unchecked")
	private List<FoodDescription> fetchByCriteria(DetachedCriteria criteria) {
		return getTemplate().findByCriteria(criteria);
	}
}
